<script lang="ts" setup>
  import { onMounted, ref } from 'vue'
  import {
    workClientStrategyPageSelect,
    moduleGetDetail,
    getWorkSlaSelect,
    moduleSave,
  } from '@/api/basic'
  import { Warning } from '@element-plus/icons-vue'
  import { ElMessage, FormInstance } from 'element-plus'
  import _ from 'lodash'
  import { SlaRuleOptions } from './types'
  import { OrderSetAPIRequestParam } from '@/typings/api/ParamSet/OrderSet'
  import autoFixedDecimal from '@/utils/money'
  import { useGetDepartmentOptions } from '@/services/module/department/useOptions'

  const {
    options: departmentOptions,
    getOptionsLoading: getDepartmentOptionsLoading,
    getOptions: getDepartmentOptions,
  } = useGetDepartmentOptions()

  const props = defineProps({
    mode: {
      type: String,
      default: () => 'edit',
    },
    moduleId: {
      type: String,
      required: true,
    },
  })

  // 分配客服规则搜索名称
  const workClientStrategyName = ref('')

  // 分配客服规则下拉数据
  const clientStrategyOption = ref([])

  // form组件实例
  const formRef = ref<FormInstance | null>(null)

  // 类型下拉数据
  const typeOptional = ref([
    { value: 1, label: '安装' },
    { value: 2, label: '维修' },
    { value: 3, label: '保养' },
    { value: 4, label: '其他' },
  ])

  // 获取表单数据加载状态 - 只有编辑时才能为true
  const getFormDataLoading = ref(false)

  // 验证规则
  const rules = ref({
    name: [
      { required: true, message: '请输入模块名称', trigger: 'blur' },
      { max: 10, message: '最多10个字符', trigger: 'blur' },
    ],
    inSourcingPrice: [
      { required: true, message: '请输入保内费用', trigger: ['blur', 'change'] },
      {
        pattern: /^0$|^0\.\d{1,2}$|^[1-9]{1}\d{0,6}(\.\d{1,2})?$/g,
        message: '仅允许输入7位整数，或输入7位整数带两位小数',
        trigger: ['blur', 'change'],
      },
    ],
    outSourcingPrice: [
      { required: true, message: '请输入保外费用', trigger: ['blur', 'change'] },
      {
        pattern: /^0$|^0\.\d{1,2}$|^[1-9]{1}\d{0,6}(\.\d{1,2})?$/g,
        message: '仅允许输入7位整数，或输入7位整数带两位小数',
        trigger: ['blur', 'change'],
      },
    ],
    warrantyDay: [
      { required: true, message: '请输入质保天数', trigger: ['blur', 'change'] },
      {
        pattern: /^0$|^[1-9]{1}\d{0,5}$/g,
        message: '质保天数输入错误，请输入 >=0 的六位整数',
        trigger: ['blur', 'change'],
      },
    ],
    callPhoneType: [
      { required: true, message: '请选择拨打电话类型', trigger: ['blur', 'change'] },
      {
        pattern: /^[01]/g,
        message: '请选择拨打电话类型',
        trigger: ['blur', 'change'],
      },
    ],
    autoCheckSuspend: [{ required: true, message: '请选择挂起审核', trigger: ['blur', 'change'] }],
    saveDataMethod: [{ required: true, message: '请选择工单挂起', trigger: ['blur', 'change'] }],
    departmentIds: [{ required: true, message: '请选择部门', trigger: ['blur', 'change'] }],
  })

  // 表单数据
  const form = ref<OrderSetAPIRequestParam.AddOrUpdateOrderModule>({
    id: '',
    name: '',
    enableWarrantyOrder: true,
    overinsured: false, // 质保状态，是否保外：false-保内，true-保外
    inSourcingPrice: 0, // 保内费用
    outSourcingPrice: 0, // 保外费用
    status: false,
    reservationTimeType: 2, // 预约时间类型：1-不启用，2-24小时，3-预约时间范围
    reservationStartTime: '', // 预约开始时间，仅传小时
    reservationEndTime: '', // 预约结束时间，仅传小时
    type: 1,
    warrantyDay: 30,
    autoDispatchClient: false, // 	是否自动分配客服：false-否，true-是
    workClientStrategyId: '', // 工单客服分派策略ID
    autoDispatchNetwork: true, // 	是否自动分配部门：false-否，true-是
    mobileCreateOrderShow: true, // 是否移动报单端展示：false-不显示，true-显示
    enableStatementVerifCode: false, //是否启用结单核销码：false-不启用，true-启用,示例值(true)
    statementVerifCodeType: 1, //结单核销码类型：1-随机，2-固定；当enableStatementVerifCode=true时生效,示例值(1)
    enableSign: false, // 是否开启签到
    signType: 1, // 签到方式：1-定位签到，2-拍照签到
    enableSecurityWatermark: true, // 是否启用拍照防伪作弊水印：false-关闭，true-开启
    signRange: 0, // 签到范围，单位：米
    callPhoneType: 0, // 拨打电话类型：0-关闭，1-必须拨打
    enableSuspend: false, // 是否启用挂起工单：false-关闭，true-开启
    autoCheckSuspend: false, // 是否自动挂起审核通过：false-人工审核，true-自动审核通过
    workSlaId: '', // 工单Sla规则ID
    departmentIds: [],
  })

  // 初始化表单
  const initForm = () => {
    form.value.id = props.mode === 'edit' ? props.moduleId : ''
    form.value.name = ''
    form.value.enableWarrantyOrder = true
    form.value.overinsured = false // 质保状态，是否保外：false-保内，true-保外
    form.value.inSourcingPrice = 0 // 保内费用
    form.value.outSourcingPrice = 0 // 保外费用
    form.value.status = false
    form.value.reservationTimeType = 2 // 预约时间类型：1-不启用，2-24小时，3-预约时间范围
    form.value.reservationStartTime = '' // 预约开始时间，仅传小时
    form.value.reservationEndTime = '' // 预约结束时间，仅传小时
    form.value.type = 1
    form.value.warrantyDay = 30
    form.value.autoDispatchClient = false // 	是否自动分配客服：false-否，true-是
    form.value.workClientStrategyId = '' // 工单客服分派策略ID
    form.value.autoDispatchNetwork = true // 	是否自动分配部门：false-否，true-是
    form.value.mobileCreateOrderShow = true
    form.value.enableStatementVerifCode = false //是否启用结单核销码
    form.value.statementVerifCodeType = 1 //结单核销码类型
    form.value.enableSign = false // 是否开启签到
    form.value.signType = 1 // 签到方式：1-定位签到，2-拍照签到
    form.value.signRange = 0 // 签到范围，单位：米
    form.value.callPhoneType = 0 // 拨打电话类型：0-关闭，1-必须拨打
    form.value.enableSuspend = false // 是否启用挂起工单：false-关闭，true-开启
    form.value.autoCheckSuspend = false // 是否自动挂起审核通过：false-人工审核，true-自动审核通过
    form.value.workSlaId = '' // 工单Sla规则ID
    form.value.departmentIds = []
  }

  // 获取分配客服规则下拉选项加载
  const getClientStrategyOptionLoading = ref(false)

  // 获取分配客服规则Api
  const clientStrategyApi = async () => {
    getClientStrategyOptionLoading.value = true
    const searchData = {
      limit: 50,
      name: workClientStrategyName.value,
      page: 1,
    }
    const res = await workClientStrategyPageSelect(searchData)
    clientStrategyOption.value = res.data.data.rows
    getClientStrategyOptionLoading.value = false
  }

  // 客服分配规则远程搜索
  const workClientStrategyRemoteMethod = _.throttle((name: string) => {
    if (workClientStrategyName.value !== name) {
      workClientStrategyName.value = name
      clientStrategyApi()
    }
  }, 500)

  // 获取sla规则下拉选项关键字
  const getSlaRuleOptionsKeyword = ref('')

  // 获取sla规则下拉选项加载
  const getSlaRuleOptionsLoading = ref(false)

  // sla规格下拉选项
  const slaRuleOptions = ref<Array<SlaRuleOptions>>([])

  /**
   * 获取SLA下拉选项
   */
  const handleGetSlaRuleOptions = _.throttle((query: string) => {
    if (getSlaRuleOptionsKeyword.value !== query) {
      getSlaRuleOptionsKeyword.value = query
      getSlaRuleOptionsFn(getSlaRuleOptionsKeyword.value)
    }
  }, 500)

  /**
   * 获取sla规则下拉选项犯法
   * @param {string} query - 关键字
   */
  const getSlaRuleOptionsFn = async (query: string) => {
    getSlaRuleOptionsLoading.value = true
    const param = {
      name: query,
      limit: 0,
      page: 0,
    }

    const res = await getWorkSlaSelect(param)
    slaRuleOptions.value = res.data.data.rows
    getSlaRuleOptionsLoading.value = false
  }

  // 保存加载
  const saveLoading = ref(false)

  /**
   * 保存方法
   */
  const save = async () => {
    if (!formRef.value) return false
    if (
      form.value.reservationTimeType == 3 &&
      (!form.value.reservationStartTime || !form.value.reservationEndTime)
    ) {
      ElMessage({
        message: '预约时间范围不能为空',
        type: 'warning',
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return
    }
    try {
      await formRef.value.validate()
      saveLoading.value = true
      const res = await moduleSave(form.value)
      ElMessage({
        type: res.data.success ? 'success' : 'error',
        message: res.data.message,
        duration: 5000,
        plain: true,
        showClose: true,
      })
      return res.data.success
    } finally {
      saveLoading.value = false
    }
  }

  onMounted(async () => {
    initForm()
    await clientStrategyApi()
    if (props.mode === 'edit') {
      getFormDataLoading.value = true
      const res = await moduleGetDetail(props.moduleId)
      getFormDataLoading.value = false
      Object.assign(form.value, res.data.data.row)
      if (form.value.reservationEndTime === null) {
        form.value.reservationEndTime = ''
      }
      form.value.departmentIds = [res.data.data.row.departmentId]
      if (form.value.workClientStrategyId == 0) {
        form.value.workClientStrategyId = ''
      }
    }
  })

  defineExpose({
    form,
    saveLoading,
    initForm,
    save,
    getSlaRuleOptionsFn,
    getDepartmentOptions,
  })
</script>

<template>
  <el-form
    ref="formRef"
    label-position="top"
    inline-message
    class="modal_form_content"
    :rules="rules"
    :model="form"
    :loading="getFormDataLoading || saveLoading"
  >
    <!-- 模块类型 -->
    <el-form-item label="模块类型" required>
      <el-select v-model="form.type" size="large" placeholder="请选择">
        <el-option
          v-for="item in typeOptional"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>

    <!-- 模块名称 -->
    <el-form-item label="模块名称" prop="name">
      <el-input v-model.trim="form.name" clearable placeholder="请输入名称" />
    </el-form-item>

    <div style="display: grid; grid-template-columns: repeat(2, 1fr)">
      <!-- 质保状态 -->
      <el-form-item label="质保状态" class="same_line">
        <el-radio-group v-model="form.overinsured">
          <el-radio :value="false" size="small">在保</el-radio>
          <el-radio :value="true" size="small">过保</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 工单质保 -->
      <el-form-item label="工单质保" class="same_line">
        <el-radio-group v-model="form.enableWarrantyOrder">
          <el-radio :value="true" size="small">启用</el-radio>
          <el-radio :value="false" size="small">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </div>

    <!-- 质保周期 -->
    <el-form-item label="质保周期" prop="warrantyDay">
      <el-input v-model.trim="form.warrantyDay" maxlength="6" clearable placeholder="请输入天数" />
    </el-form-item>

    <!-- 保内费用 -->
    <el-form-item label="保内费用" prop="inSourcingPrice">
      <el-input
        v-model.trim="form.inSourcingPrice"
        clearable
        maxlength="10"
        placeholder="请输入保存费用"
      />
    </el-form-item>

    <!-- 保外费用 -->
    <el-form-item label="保外费用" prop="outSourcingPrice">
      <el-input
        v-model.trim="form.outSourcingPrice"
        clearable
        maxlength="10"
        placeholder="请输入保外费用"
      />
    </el-form-item>

    <!-- SLA规则 -->
    <el-form-item label="SLA规则" prop="slaRule">
      <el-select
        v-model="form.workSlaId"
        placeholder="请选择"
        filterable
        clearable
        :filter-method="handleGetSlaRuleOptions"
        :loading="getSlaRuleOptionsLoading"
      >
        <el-option
          v-for="(slaRule, slaRuleIndex) in slaRuleOptions"
          :key="slaRuleIndex"
          :label="slaRule.name"
          :value="slaRule.id"
        />
      </el-select>
    </el-form-item>

    <div style="display: grid; grid-template-columns: repeat(2, 1fr)">
      <!--拨打电话类型-->
      <el-form-item required prop="callPhoneType" label="拨打电话" class="same_line">
        <el-radio-group v-model="form.callPhoneType">
          <el-radio :value="0" size="small">关闭</el-radio>
          <el-radio :value="1" size="small">
            <div style="display: flex; align-items: center; gap: 6px">
              <span class="bg_text">必须拨打</span>
              <el-tooltip effect="dark" content="开启后，工单必须拨打电话才能操作" placement="top">
                <el-icon size="16" color="#000">
                  <Warning />
                </el-icon>
              </el-tooltip>
            </div>
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 预约时间 -->
      <el-form-item label="预约时间" class="same_line" prop="reservationTimeType">
        <el-radio-group v-model="form.reservationTimeType">
          <el-radio :value="1" size="small">不启用</el-radio>
          <el-radio :value="2" size="small">24小时</el-radio>
          <el-radio :value="3" size="small">预约时间范围</el-radio>
        </el-radio-group>
      </el-form-item>
    </div>

    <!-- 预约时间范围 -->
    <el-form-item v-if="form.reservationTimeType === 3" label="预约时间范围">
      <div style="display: flex; width: 100%; column-gap: 5px">
        <el-time-select
          v-model="form.reservationStartTime"
          class="reservationTime-el-time-select"
          :max-time="form.reservationEndTime"
          placeholder="预约开始时间"
          step="2:00"
          start="06:00"
          end="23:00"
          size="small"
          :disabled="form.reservationTimeType !== 3"
        />
        <span class="reservationTime-span">~</span>
        <el-time-select
          v-model="form.reservationEndTime"
          class="reservationTime-el-time-select"
          :min-time="form.reservationStartTime"
          placeholder="预约结束时间"
          step="2:00"
          start="06:00"
          end="23:00"
          size="small"
          :disabled="form.reservationTimeType !== 3"
        />
      </div>
    </el-form-item>

    <div style="display: grid; grid-template-columns: repeat(2, 1fr)">
      <!-- 移动端可见 -->
      <el-form-item label="移动端显示" class="same_line">
        <el-radio-group v-model="form.mobileCreateOrderShow" class="el-group">
          <el-radio :value="true" size="small">显示 </el-radio>
          <el-radio :value="false" size="small">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 分配客服 -->
      <el-form-item label="分配客服" class="same_line" prop="autoDispatchClient">
        <el-radio-group v-model="form.autoDispatchClient">
          <el-radio :value="false" size="small">人工分配</el-radio>
          <el-radio :value="true" size="small">自动分配</el-radio>
        </el-radio-group>
      </el-form-item>
    </div>

    <!-- 分配客服规则 -->
    <el-form-item label="分配规则">
      <el-select
        v-model="form.workClientStrategyId"
        :disabled="!form.autoDispatchClient"
        placeholder="请选择分配规则"
        filterable
        :filter-method="workClientStrategyRemoteMethod"
        clearable
        :loading="getClientStrategyOptionLoading"
      >
        <el-option
          v-for="item in clientStrategyOption"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>

    <!-- 分派部门 -->
    <!-- <el-form-item label="分派部门" class="form-item" prop="autoDispatchNetwork">
            <el-radio-group v-model="form.autoDispatchNetwork" class="el-group">
              <el-radio style="width: 6vw" :value="false">
                <span class="bg_text">人工派单</span>
              </el-radio>
              <el-radio :value="true">
                <span class="bg_text">自动派单</span>
              </el-radio>
            </el-radio-group>
          </el-form-item> -->

    <!-- 分派规则 -->
    <!-- 后面有需要再添加 -->
    <!-- <el-form-item label="分派规则" class="form-item" prop="autoDispatchNetwork">
          <el-select>
            <el-option>请选择</el-option>
          </el-select>
        </el-form-item> -->

    <div style="display: grid; grid-template-columns: repeat(2, 1fr)">
      <!-- 结单核销码 - 启用/禁用 -->
      <el-form-item label="结单核销码" class="same_line">
        <el-radio-group v-model="form.enableStatementVerifCode">
          <el-radio :value="true" size="small">启用</el-radio>
          <el-radio :value="false" size="small">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 核销码内容 -->
      <el-form-item label="核销码内容" class="same_line">
        <el-radio-group
          v-model="form.statementVerifCodeType"
          :disabled="!form.enableStatementVerifCode"
        >
          <el-radio :value="1" size="small">
            <div style="display: flex; align-items: center; gap: 5px">
              <span class="bg_text">随机</span>
              <el-tooltip effect="dark" content="每单随机生成不同的核销码" placement="top">
                <el-icon size="16" color="#000"><Warning /></el-icon>
              </el-tooltip>
            </div>
          </el-radio>
          <el-radio :value="2" size="small">
            <div style="display: flex; align-items: center; gap: 5px">
              <span class="bg_text">固定</span>
              <el-tooltip effect="dark" content="每单生成固定的核销码" placement="top">
                <el-icon size="16" color="#000"><Warning /></el-icon>
              </el-tooltip>
            </div>
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </div>

    <div style="display: grid; grid-template-columns: 150px 200px 170px; column-gap: 48px">
      <!-- 开启签到 -->
      <el-form-item label="开启签到" class="same_line">
        <el-radio-group v-model="form.enableSign">
          <el-radio :value="true" size="small">启用</el-radio>
          <el-radio :value="false" size="small">关闭</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 签到方式 -->
      <el-form-item label="签到方式" class="same_line">
        <el-radio-group v-model="form.signType" :disabled="!form.enableSign">
          <el-radio :value="1" size="small">定位签到</el-radio>
          <el-radio :value="2" size="small">拍照签到</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 防作弊水印 -->
      <el-form-item label="防作弊水印" class="same_line">
        <el-radio-group
          v-model="form.enableSecurityWatermark"
          :disabled="form.signType !== 2 || !form.enableSign"
        >
          <el-radio :value="true" size="small">启用</el-radio>
          <el-radio :value="false" size="small">关闭</el-radio>
        </el-radio-group>
      </el-form-item>
    </div>

    <!-- 签到范围 -->
    <el-form-item label="签到范围">
      <div style="display: flex; width: 100%; align-items: center">
        <el-input
          v-model.trim="form.signRange"
          :disabled="form.signType !== 1 || !form.enableSign"
          placeholder="输入范围：米"
          auto-fixed-decimal
          maxlength="8"
          @input="form.signRange = autoFixedDecimal(form.signRange, 0)"
          @change="form.signRange = Number(form.signRange)"
        >
          <template #append><span style="font-size: 12px">米</span> </template>
        </el-input>
        &nbsp;&nbsp;
        <el-tooltip effect="dark" content="定位必须在签到地址范围内多少米" placement="top">
          <i class="iconfont icon-warning" style="color: #e69103; font-size: 16px"></i>
        </el-tooltip>
      </div>
    </el-form-item>

    <div class="last-line">
      <div class="status">
        <!-- 状态 -->
        <el-form-item label="状态" class="same_line">
          <el-radio-group v-model="form.status">
            <el-radio :value="false" size="small">启用</el-radio>
            <el-radio :value="true" size="small">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <div class="order-hang-up">
        <!--工单挂起-->
        <el-form-item label="工单挂起" required class="same_line" prop="enableSuspend">
          <div class="switch-container">
            <el-switch v-model="form.enableSuspend" size="small" />
            <span v-if="form.enableSuspend">启用</span>
            <span v-else>关闭</span>
          </div>
        </el-form-item>
      </div>

      <div class="hang-up-check">
        <!--挂起审核-->
        <el-form-item label="挂起审核" required class="same_line" prop="autoCheckSuspend">
          <el-radio-group v-model="form.autoCheckSuspend">
            <el-radio :value="true" size="small">无需审核</el-radio>
            <el-radio :value="false" size="small">需要审核</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
    </div>

    <!-- 所属部门 -->
    <el-form-item label="所属部门" prop="departmentIds">
      <el-select
        v-model="form.departmentIds"
        placeholder="请选择所属部门"
        size="large"
        multiple
        :disabled="props.mode === 'edit'"
      >
        <el-option
          v-for="(option, optionIndex) in departmentOptions"
          :key="optionIndex"
          :label="option.name"
          :value="option.id"
        />
      </el-select>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
  :deep(.el-radio__input.is-disabled) {
    span {
      background: #f5f7fa !important;
      border-color: #e4e7ed !important;
    }

    span.el-radio__label {
      span {
        color: #999 !important;
      }
    }
  }

  :deep(.el-radio.is-disabled.is-checked) {
    span.el-radio__label {
      span {
        color: #999 !important;
      }
    }
  }

  .last-line {
    display: flex;
    justify-content: space-between;

    .order-hang-up {
      :deep(.el-form-item) {
        .el-form-item__content {
          .switch-container {
            height: 16px !important;
            display: flex;
            column-gap: 5px;

            span {
              line-height: 16px;
            }
          }
          .el-switch {
            height: 16px;
          }
        }
      }
    }
  }
</style>
